package com.mars.upms.rpc.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mars.base.common.exception.AppException;
import com.mars.base.service.support.BaseService;
import com.mars.upms.dao.mapper.UpmsCompanyMapper;
import com.mars.upms.dao.mapper.UpmsUserCompanyDeptAssignMapper;
import com.mars.upms.entity.UpmsCompany;
import com.mars.upms.entity.UpmsUserCompanyDeptAssign;
import com.mars.upms.rpc.api.UpmsCompanyService;

@Service
public class UpmsCompanyServiceImpl extends BaseService<UpmsCompany, Integer> implements UpmsCompanyService {
	
	@Autowired
	private UpmsCompanyMapper mapper ;
	
	@Autowired
	private UpmsUserCompanyDeptAssignMapper upmsUserCompanyDeptAssignMapper;
	
	@Override
	public List<UpmsCompany> selectRoot() {
		return this.mapper.selectRoot();
	}
	
	@Override
	public int delete(Integer id) throws AppException {
		recursiveDelete(id);
		return 0;
	}
	
	private void recursiveDelete(Integer id) {
		List<UpmsCompany> loadChildrenNode = this.selectChildren(id) ;
		if(null != loadChildrenNode) {
			for (UpmsCompany company : loadChildrenNode) {
				recursiveDelete(company.getId());
			}
		}
		super.delete(id) ;
	}

	@Override
	public List<UpmsCompany> selectChildren(Integer pid) {
		return this.mapper.selectChildren(pid);
	}

	@Override
	public List<UpmsCompany> tree(UpmsCompany entity) {
		List<UpmsCompany> list = new ArrayList<UpmsCompany>() ;
		
		List<UpmsCompany> selectRoot = this.selectRoot() ;
		for (UpmsCompany company : selectRoot) {
			list.add(recursive(company)) ;
		}
		return list;
	}
	
	private UpmsCompany recursive(UpmsCompany company) {
		
		List<UpmsCompany> selectChildren = this.selectChildren(company.getId()) ;
		if(null != selectChildren && !selectChildren.isEmpty()) {
			List<UpmsCompany> children = new ArrayList<UpmsCompany>() ;
			
			for (UpmsCompany child : selectChildren) {
				children.add(recursive(child)) ;
			}
			
			company.setChildren(children);
		}
		return company ;
	}

	@Override
	public void removeCompanyAssignAllUser(Integer companyId) {
		UpmsUserCompanyDeptAssign entity = new UpmsUserCompanyDeptAssign() ;
		entity.setCompanyId(companyId);
		this.upmsUserCompanyDeptAssignMapper.delete(entity) ;		
	}
	
}
